<?php
require_once("database.php");

function answers_POST($id, $qid)
{
	$db = getDBConnection();
	
	$data = json_decode(file_get_contents('php://input'));
	
	$uid = $data->uid;
	$answer = $data->answer;	
	
	$time = time();
	$mysqldate = date( 'Y-m-d H:i:s', $time );
	
	$sql = "INSERT INTO answer VALUES('".$id."', '".$qid."', '".$uid."', '".$answer."', '".$mysqldate."')";
	mysqli_query($db, $sql);
	
	return 0;
}

function answers_GET($id, $qid)
{
	$db = getDBConnection();
	
	$sql = "SELECT uid, answer, time FROM answer WHERE id = '".$id."' AND qid = '".$qid."'";
	$result = mysqli_query($db, $sql);
	$answer_data = array();
	
	$count = 0;
	if(($count = mysqli_num_rows($result)) > 0)
	{
		for($i = 0; $i < $count; $i++)
		{
			$row = mysqli_fetch_assoc($result);
			$answer_data[$i]["id"] = $id;
			$answer_data[$i]["qid"] = $qid;
			$answer_data[$i]["uid"] = $row["uid"];
			$answer_data[$i]["answer"] = $row["answer"];
			$answer_data[$i]["time"] = strtotime($row["time"]);
		}
	}else
	{
		printErrorCode(404);
	}
	
	return $answer_data;
}

function answers_DELETE($id, $qid)
{
	$db = getDBConnection();
	
	$sql = "DELETE FROM answer WHERE id = '".$id."' AND qid = '".$qid."'";
	mysqli_query($db, $sql);
	
	return 0;
}

function answer_GET($id, $qid, $uid)
{
	$db = getDBConnection();
	$answer_data = array();
	
	$sql = "SELECT * FROM answer WHERE qid = '".$qid."' AND id = '".$id."' AND uid = '".$uid."'";
	$data = mysqli_query($db, $sql);
	
	if(mysqli_num_rows($data) > 0)
	{
		$row = mysqli_fetch_assoc($data);
		
		$answer_data["id"] = $row["id"];
		$answer_data["qid"] = $row["qid"];
		$answer_data["uid"] = $row["uid"];
		$answer_data["answer"] = $row["answer"];
		$answer_data["time"] = strtotime($row["time"]);
		
	}else
	{
		printErrorCode(404);
	}

	return $answer_data;
}

function answer_PUT($id, $qid, $uid)
{
	$db = getDBConnection();	
	$data = json_decode(file_get_contents('php://input'));
	
	if(!$data)
	{
		return 0;
	}
	
	$answer = $data->answer;
	$time = date( 'Y-m-d H:i:s', time() );
	
	$sql = "UPDATE answer SET answer = '".$answer."', time = '".$time."' WHERE qid = '".$qid."' AND id = '".$id."' AND uid = '".$uid."'";
	mysqli_query($db, $sql);

	return 0;
}

function answer_DELETE($id, $qid, $uid)
{
	$db = getDBConnection();	
	
	$sql = "DELETE FROM answer WHERE qid = '".$qid."' AND id = '".$id."' AND uid = '".$uid."'";
	mysqli_query($db, $sql);

	return 0;
}

?>